/*-
 * Generic inheritance graph.
 *
 * Copyright (c) 2010 Alex Suhan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer
 * in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Vector;
import java.util.Set;


public class InheritanceGraph<T>
{
    private HashMap<T, PredSucc> inhMap;
    
    /*
     * contine informatii despre legaturile unui nod: campul 'pred' este clasa
     * de la care se mosteneste in mod direct, campul 'succList' este lista
     * de succesori directi
     */
    private class PredSucc
    {
        private T pred;
        private LinkedList<T> succList;
        
        PredSucc()
        {
            succList = new LinkedList<T>();
        }
        
        T getPred()
        {
            return pred;
        }
        
        Iterator<T> getSuccList()
        {
            return succList.iterator();
        }
        
        void setPred(T pred)
        {
            this.pred = pred;
        }
        
        void addSucc(T succ)
        {
            succList.add(succ);
        }
    }
    
    public InheritanceGraph()
    {
        inhMap = new HashMap<T, PredSucc>();
    }
    
    /* adauga legatura base->derived */
    public void addLink(T derived, T base)
    {
        if (inhMap.get(derived) == null)
            inhMap.put(derived, new PredSucc());
        if (inhMap.get(base) == null)
            inhMap.put(base, new PredSucc());
        
        PredSucc derivedInfo = inhMap.get(derived);
        PredSucc baseInfo = inhMap.get(base);
        
        derivedInfo.setPred(base);
        baseInfo.addSucc(derived);
    }
    
    private Vector<T> getPathHelper(T derived)
    {
        Vector<T> path = new Vector<T>();
        T crt = derived;
        
        while (crt != null)
        {
            path.add(crt);
            PredSucc crtInfo = inhMap.get(crt);
            if (crtInfo == null)
                break;
            crt = crtInfo.getPred();
        }
        
        return path;
    }
    
    /* returneaza calea de mostenire incepand cu clasa derivata */
    public Iterator<T> getInheritancePath(T derived)
    {
        return getPathHelper(derived).iterator();
    }
    
    /*
     * returneaza stramosul comun cel mai particular; functie utila pentru
     * uniuni de tipuri (necesare pentru case tipat si if)
     */
    public T getCommonAncestor(T derived1, T derived2)
    {
        Vector<T> path1 = getPathHelper(derived1);
        Vector<T> path2 = getPathHelper(derived2);
        int idx1 = path1.size() - 1;
        int idx2 = path2.size() - 1;
        
        T ancestor = null;
        
        while (idx1 >= 0 && idx2 >= 0)
        {
            if (path1.get(idx1) == path2.get(idx2))
                ancestor = path1.get(idx1);
            else
                break;
            idx1--;
            idx2--;
        }
        
        return ancestor;
    }
    
    private boolean dfsHelper(T crt, T start)
    {
        if (crt == start)
            return true;
        Iterator<T> succIt = inhMap.get(crt).getSuccList();
        
        while (succIt.hasNext())
        {
            T succ = succIt.next();
            if (dfsHelper(succ, start))
                return true;
        }
        
        return false;
    }
    
    /*
     * parcurge dfs incepand cu nodul 'start', returneaza 'true' daca
     * detecteaza ciclu incepand cu nodul 'start'
     */
    private boolean dfs(T start)
    {
        Iterator<T> succIt = inhMap.get(start).getSuccList();
        
        while (succIt.hasNext())
        {
            T succ = succIt.next();
            if (dfsHelper(succ, start))
                return true;
        }
        
        return false;
    }
    
    /* cauta un ciclu si returneaza nodul lui de start, 'null' daca nu exista */
    public T cycleStart()
    {
        Set<T> keys = inhMap.keySet();
        Iterator<T> keysIt = keys.iterator();
        
        while (keysIt.hasNext())
        {
            T start = keysIt.next();
            if (dfs(start))
            {
                return start;
            }
        }
        
        return null;
    }
    
    /* inchidere tranzitiva pentru relatia de mostenire */
    public boolean conforming(T derived, T base)
    {
        Iterator<T> pathIt = getInheritancePath(derived);
        
        while (pathIt.hasNext())
        {
            T crt = pathIt.next();
            if (crt == base)
                return true;
        }
        
        return false;
    }
    
    public boolean isDefined(T toCheck)
    {
        return (inhMap.get(toCheck) != null);
    }
}
